import {createRouter, createWebHistory, RouteRecordRaw} from 'vue-router'

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'Home',
        component: () => import(/* webpackChunkName: "home" */'../components/Home.vue')
    },
    {
        path: '/login',
        name: 'LoginForm',
        component: () => import(/* webpackChunkName: "login" */'../components/LoginForm.vue')
    },
    {
        path: '/user-list',
        name: 'UserList',
        component: () => import(/* webpackChunkName: "user-list" */'../components/UserList.vue')
    },
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),  // 使用 HTML5 History 模式
    routes // 路由配置
})
// 路由守卫：检查登录状态
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token');
    if (to.name !== '/login' && !token) {
        next({name: 'login'})
    } else if (to.name === '/login' && token) {
        next({name: 'home'})
    } else {
        next()
    }
})
export default router
